package com.zxq.dlt645.frame;

import com.zxq.factory.FastFrame;
import com.zxq.factory.annotate.BigLittleEndianMark;
import com.zxq.factory.annotate.DecoderField;
import com.zxq.factory.annotate.EncoderField;
import com.zxq.factory.annotate.Frame;
import com.zxq.factory.enums.EField;
import com.zxq.factory.enums.ETrimMethod;
import lombok.Data;

@Frame
@Data
public class DLT645Frame {

    @EncoderField(len = 1)
    @DecoderField(param = 1)
    Integer  headFlag = 0x68;

    @EncoderField(sequence = 1,field = EField.Long,len = 6)
    @DecoderField(sequence = 1,field = EField.Long,param = 6)
    @BigLittleEndianMark(serial = "654321")
    Long  address;

    @EncoderField(sequence = 2,len = 1)
    @DecoderField(sequence = 2,param = 1)
    Integer  frameFlag = 0x68;

    @EncoderField(sequence = 3,len = 1)
    @DecoderField(sequence = 3,param = 1)
    Integer  cmd;

    @EncoderField(sequence = 4,len = 1)
    @DecoderField(sequence = 4,param = 1)
    Integer len;

    @EncoderField(sequence = 5,field = EField.Bytes)
    @DecoderField(sequence = 5,field = EField.Bytes,method = ETrimMethod.Tail)
    byte[] data;

    @EncoderField(sequence = 6,field = EField.Byte,len = 1)
    @DecoderField(sequence = 6,field = EField.Byte,param = 1)
    byte crc;

    @EncoderField(sequence = 7,len = 1)
    @DecoderField(sequence = 7,param = 1)
    Integer tailFlag = 0x16;


    /**
     * 计算长度
     */
    public void countLen() {
        if(data != null) {
            len = data.length;
        }
    }


    public void countCrc() {
        if(data != null) {
          byte[] frame =  FastFrame.encoder(this);
         // System.out.println("crc:" + HexBin.encode(frame));
          byte sum = 0;
          for(int i = 0; i < frame.length - 2; i++) {
                  sum += frame[i];
          }
         crc = sum;
        }
    }

    /**
     * 编码时候每个字节+0x33
     */
    public void decorateEncoder() {
        for(int i = 0; i < data.length; i++) {
           data[i] += 0x33;
        }
    }

    /**
     * 解码时候每个字节-0x33
     */
    public void decorateDecoder() {
        for(int i = 0; i < data.length; i++) {
            data[i] -= 0x33;
        }
    }



}
